package com.itheima.edu.info.manager.dao;

import com.itheima.edu.info.manager.domain.Student;

import java.io.*;
import java.util.ArrayList;

public class OtherStudentDao03 implements BaseStudentDao {
    // 创建集合容器
    private static ArrayList<Student> stus = new ArrayList<>();

    static {
        try {
            InputStreamReader isr = new InputStreamReader(new FileInputStream("itheima-edu-info-manager\\student3.txt"), "GBK");
            char[] chs = new char[1024];
            int len;

            StringBuilder sb = new StringBuilder();
            while ((len = isr.read(chs)) != -1) {
                sb.append(new String(chs, 0, len));
            }
            String stuStr = sb.toString();

            String[] split = stuStr.split(System.lineSeparator());
            for (int i = 0; i < split.length; i++) {
                String[] strings = split[i].split(",");
                Student stu = new Student(strings[0], strings[1], strings[2], strings[3]);
                stus.add(stu);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 添加学生方法
    public boolean addStudent(Student stu) {
        stus.add(stu);
        reSave();
        return true;
    }

    // 查看所有学生对象并返回
    public Student[] findAllStudent() {
        Student[] students = new Student[stus.size()];

        for (int i = 0; i < students.length; i++) {
            students[i] = stus.get(i);
        }
        return students;
    }

    //删除学生
    public void deleteStudent(String deleteId) {
        int index = getIndex(deleteId);
        // 调用集合中的remove()方法来实现删除功能
        stus.remove(index);
        reSave();
    }

    public int getIndex(String deleteId) {
        int index = -1;
        for (int i = 0; i < stus.size(); i++) {
            Student stu = stus.get(i);
            if (stu != null && stu.getId().equals(deleteId)) {
                index = i;
                break;
            }
        }
        return index;
    }

    //修改学生
    public void updateStudent(String updateId, Student newStu) {
        // 1. 查找updateId, 在容器中的索引位置
        int index = getIndex(updateId);
        // 索引位置的数据替换成新的数据
        stus.set(index, newStu);
        reSave();
    }

    private void reSave() {
        try {
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("itheima-edu-info-manager\\student3.txt"), "GBK");
            for (Student student : stus) {
                String s = student.toString();
                osw.write(s);
                osw.write(System.lineSeparator());
                osw.flush();
            }
            osw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
